package com.example.myblog.config;

import com.example.myblog.exception.BaseException;
import com.example.myblog.result.ResponseBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author 叶兴
 */
@Component
public class ExceptionWebMvcConfig implements WebMvcConfigurer {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add((request, response, handler, ex) -> {
            ResponseBean result;
            HashMap<String,Object> errorData = new HashMap<>();
            logger.info("请求错误,url:{}",request.getRequestURL());
            if (ex instanceof BaseException){
                BaseException baseException = (BaseException) ex;
                logger.info("错误码:{},错误信息:{}",baseException.getErrorCode(),baseException.getErrorMsg());
                errorData.put("errorCode",baseException.getErrorCode());
                errorData.put("errorMsg",baseException.getErrorMsg());
            } else if (ex instanceof HttpRequestMethodNotSupportedException) {
                logger.info("错误码:{},错误信息:{}", HttpStatus.BAD_REQUEST.value(),ex.getMessage());
                errorData.put("errorCode",HttpStatus.BAD_REQUEST.value());
                errorData.put("errorMsg","不支持该请求方式");
            } else if (ex instanceof NoHandlerFoundException) {
                logger.info("接口不存在，错误码:{},错误信息:{}",HttpStatus.NOT_FOUND.value(),ex.getMessage());
                errorData.put("errorCode",HttpStatus.NOT_FOUND.value());
                errorData.put("errorMsg","API接口:[" + request.getServletPath() + "]不存在");

            } else {
                logger.info("接口不存在，错误码:{},错误信息:{}",HttpStatus.INTERNAL_SERVER_ERROR.value(),ex.getMessage(),ex);
                errorData.put("errorCode",HttpStatus.INTERNAL_SERVER_ERROR.value());
                errorData.put("errorMsg","服务器异常，请联系管理员");
            }
            result = ResponseBean.error(errorData);
            responseResult(response,result);
            return new ModelAndView();

        });
    }

    private void responseResult(HttpServletResponse response,ResponseBean responseBean) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type","application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().write(objectMapper.writeValueAsString(responseBean));
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
}
